﻿using CastingWellEquipmentGUI.Config;
using CastingWellEquipmentGUI.Model;
using CastingWellEquipmentGUI.Utils;
using CastingWellEquipmentGUI.ViewModel.Common.Command;
using CastingWellEquipmentGUI.ViewModel.Common.WindowsManager;
using Confluent.Kafka;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Messaging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;

namespace CastingWellEquipmentGUI.ViewModel.Pages
{
    /// <summary>
    /// 铸井公辅ViewModel
    /// </summary>
    public class CastWellPublicAuxiliaryPageViewModel : ViewModelBase
    {

        #region 变量/常量
        /// <summary>
        /// 当前窗体名称
        /// </summary>
        private const string showPageTitle = "CastWellPublicAuxiliaryPage";
        #endregion 变量/常量

        #region 页面属性

        #region 气体润滑
        /// <summary>
        /// 气体润滑PV
        /// </summary>
        public string Lable_Gas_PV
        {
            get { return TagTool.GetTagValueByFormNameAndControlName(showPageTitle, "Lable_Gas_PV"); }
        }
        private string _Button_SP_Gas;
        /// <summary>
        /// SP值设定
        /// </summary>
        public string Button_SP_Gas
        {
            get { return _Button_SP_Gas; }
            set
            {
                if (KafkaHelper.SendGatewayChangeTagMessage(showPageTitle, "Button_SP_Gas", value))
                {
                    _Button_SP_Gas = value;
                    RaisePropertyChanged("Button_SP_Gas");
                }
            }
        }
        private string _Button_CV_Gas;
        /// <summary>
        /// CV值设定
        /// </summary>
        public string Button_CV_Gas
        {
            get { return _Button_CV_Gas; }
            set
            {
                if (KafkaHelper.SendGatewayChangeTagMessage(showPageTitle, "Button_CV_Gas", value))
                {
                    _Button_CV_Gas = value;
                    RaisePropertyChanged("Button_CV_Gas");
                }
            }
        }
        private bool _Button_AutoGasLubrication_Value = false;
        /// <summary>
        /// 气体润滑自动按钮标签值
        /// </summary>
        public bool Button_AutoGasLubrication_Value
        {
            get { return _Button_AutoGasLubrication_Value; }
            set { _Button_AutoGasLubrication_Value = value; RaisePropertyChanged("Button_AutoGasLubrication_Value"); }
        }
        private bool _Button_ManualGasLubrication_Value = false;
        /// <summary>
        /// 气体润滑手动按钮标签值
        /// </summary>
        public bool Button_ManualGasLubrication_Value
        {
            get { return _Button_ManualGasLubrication_Value; }
            set { _Button_ManualGasLubrication_Value = value; RaisePropertyChanged("Button_ManualGasLubrication_Value"); }
        }
        private bool _Button_ForwardGasLubrication_Value = false;
        /// <summary>
        /// 气体润滑ON按钮标签值
        /// </summary>
        public bool Button_ForwardGasLubrication_Value
        {
            get { return _Button_ForwardGasLubrication_Value; }
            set { _Button_ForwardGasLubrication_Value = value; RaisePropertyChanged("Button_ForwardGasLubrication_Value"); }
        }
        private bool _Button_ReversalGasLubrication_Value = false;
        /// <summary>
        /// 气体润滑OFF按钮标签值
        /// </summary>
        public bool Button_ReversalGasLubrication_Value
        {
            get { return _Button_ReversalGasLubrication_Value; }
            set { _Button_ReversalGasLubrication_Value = value; RaisePropertyChanged("Button_ReversalGasLubrication_Value"); }
        }
        #endregion 气体润滑

        #region 送丝机
        /// <summary>
        /// 送丝机PV1
        /// </summary>
        public string Lable_Feeder_PV1
        {
            get { return TagTool.GetTagValueByFormNameAndControlName(showPageTitle, "Lable_Feeder_PV1"); }
        }
        // <summary>
        /// 送丝机PV2
        /// </summary>
        public string Lable_Feeder_PV2
        {
            get { return TagTool.GetTagValueByFormNameAndControlName(showPageTitle, "Lable_Feeder_PV2"); }
        }
        private string _Button_SP_Feeder;
        /// <summary>
        /// SP值设定
        /// </summary>
        public string Button_SP_Feeder
        {
            get { return _Button_SP_Feeder; }
            set
            {
                if (KafkaHelper.SendGatewayChangeTagMessage(showPageTitle, "Button_SP_Feeder", value))
                {
                    _Button_SP_Feeder = value;
                    RaisePropertyChanged("Button_SP_Feeder");
                }
            }
        }
        private string _Button_CV_Feeder;
        /// <summary>
        /// CV值设定
        /// </summary>
        public string Button_CV_Feeder
        {
            get { return _Button_CV_Feeder; }
            set
            {
                if (KafkaHelper.SendGatewayChangeTagMessage(showPageTitle, "Button_CV_Feeder", value))
                {
                    _Button_CV_Feeder = value;
                    RaisePropertyChanged("Button_CV_Feeder");
                }
            }
        }
        private bool _Button_AutoFeederLubrication_Value = false;
        /// <summary>
        /// 送丝机自动按钮标签值
        /// </summary>
        public bool Button_AutoFeederLubrication_Value
        {
            get { return _Button_AutoFeederLubrication_Value; }
            set { _Button_AutoFeederLubrication_Value = value; RaisePropertyChanged("Button_AutoFeederLubrication_Value"); }
        }
        private bool _Button_ManualFeederLubrication_Value = false;
        /// <summary>
        /// 送丝机手动按钮标签值
        /// </summary>
        public bool Button_ManualFeederLubrication_Value
        {
            get { return _Button_ManualFeederLubrication_Value; }
            set { _Button_ManualFeederLubrication_Value = value; RaisePropertyChanged("Button_ManualFeederLubrication_Value"); }
        }
        private bool _Button_ForwardFeeder_Value = false;
        /// <summary>
        /// 送丝机手动正转按钮标签值
        /// </summary>
        public bool Button_ForwardFeeder_Value
        {
            get { return _Button_ForwardFeeder_Value; }
            set { _Button_ForwardFeeder_Value = value; RaisePropertyChanged("Button_ForwardFeeder_Value"); }
        }
        private bool _Button_ReversalFeeder_Value = false;
        /// <summary>
        /// 送丝机手动反转按钮
        /// </summary>
        public bool Button_ReversalFeeder_Value
        {
            get { return _Button_ReversalFeeder_Value; }
            set { _Button_ReversalFeeder_Value = value; RaisePropertyChanged("Button_ReversalFeeder_Value"); }
        }
        #endregion 送丝机

        #region 预检测项目
        private Visibility _PreDetectionVisibility;
        /// <summary>
        /// 预检测状态
        /// 注：控制预检测框显隐
        /// </summary>
        public Visibility PreDetectionVisibility
        {
            get { return _PreDetectionVisibility; }
            set { _PreDetectionVisibility = value; RaisePropertyChanged("PreDetectionVisibility"); }
        }
        /// <summary>
        /// 气源压力正常
        /// </summary>
        public Brush Label_PreCheck1
        {
            get
            {
                if (TagTool.GetTagValueByFormNameAndControlName(showPageTitle, "Label_PreCheck1") == "true")
                {
                    return Brushes.Red;
                }
                return Brushes.Black;
            }
        }
        /// <summary>
        /// 铸盘气压正常
        /// </summary>
        public Brush Label_PreCheck2
        {
            get
            {
                if (TagTool.GetTagValueByFormNameAndControlName(showPageTitle, "Label_PreCheck2") == "true")
                {
                    return Brushes.Red;
                }
                return Brushes.Black;
            }
        }
        /// <summary>
        /// 送丝机正常
        /// </summary>
        public Brush Label_PreCheck3
        {
            get
            {
                if (TagTool.GetTagValueByFormNameAndControlName(showPageTitle, "Label_PreCheck3") == "true")
                {
                    return Brushes.Red;
                }
                return Brushes.Black;
            }
        }
        #endregion 预检测项目

        #endregion 页面属性

        #region 定义页面执行命令
        /// <summary>
        /// 气体润滑按钮点击触发
        /// </summary>
        public DelegateCommand GusButtonCommand { get; set; }
        /// <summary>
        /// 送丝机按钮点击触发
        /// </summary>
        public DelegateCommand FeederButtonCommand { get; set; }
        /// <summary>
        /// 按钮命令
        /// 气体润滑设置：SP、CV
        /// 送丝机设置：SP、CV
        /// </summary>
        public DelegateCommand ShowModalPanelCommand { get; set; }
        #endregion 定义页面执行命令

        #region 线程对象
        /// <summary>
        /// 标签值变化监听线程
        /// </summary>
        private Thread tagInfoSyncThread = null;
        #endregion 线程对象

        #region 方法
        /// <summary>
        /// 构造函数
        /// </summary>
        public CastWellPublicAuxiliaryPageViewModel()
        {
            // 初始化命令
            initCommand();
            // 初始化线程
            initThread();
            // 消息通道注册
            initMessenger();
            // 初始化基础信息
            initBaseSet();
        }

        /// <summary>
        /// 初始化基础信息
        /// </summary>
        private void initBaseSet()
        {
            // 页面初始化
            HashSet<Control> tempHashSet = SysCommon.getCurrentControl(showPageTitle);
            if (tempHashSet.Count > 0)
            {
                DoChanged(tempHashSet);
            }
            /** 设定值初始化 **/
            _Button_SP_Gas = TagTool.GetTagValueByFormNameAndControlName(showPageTitle, "Button_SP_Gas");
            RaisePropertyChanged("Button_SP_Gas");
            _Button_CV_Gas = TagTool.GetTagValueByFormNameAndControlName(showPageTitle, "Button_CV_Gas");
            RaisePropertyChanged("Button_CV_Gas");

            _Button_SP_Feeder = TagTool.GetTagValueByFormNameAndControlName(showPageTitle, "Button_SP_Feeder");
            RaisePropertyChanged("Button_SP_Feeder");
            _Button_CV_Feeder = TagTool.GetTagValueByFormNameAndControlName(showPageTitle, "Button_CV_Feeder");
            RaisePropertyChanged("Button_CV_Feeder");
        }

        /// <summary>
        /// 消息通道注册
        /// ViewModel之间数据通信使用，整个项目全局唯一
        /// </summary>
        private void initMessenger()
        {
            // 气体润滑SP设置消息队列
            Messenger.Default.Register<string>(this, showPageTitle + "Button_SP_Gas", (message) =>
            {
                Button_SP_Gas = message.ToString(); ;
            });
            // 气体润滑CV设置消息队列
            Messenger.Default.Register<string>(this, showPageTitle + "Button_CV_Gas", (message) =>
            {
                Button_CV_Gas = message.ToString(); ;
            });
            // 气送丝机SP设置消息队列
            Messenger.Default.Register<string>(this, showPageTitle + "Button_SP_Feeder", (message) =>
            {
                Button_SP_Feeder = message.ToString(); ;
            });
            // 气送丝机CV设置消息队列
            Messenger.Default.Register<string>(this, showPageTitle + "Button_CV_Feeder", (message) =>
            {
                Button_CV_Feeder = message.ToString(); ;
            });
            //页面切换执行控件刷新
            Messenger.Default.Register<string>(this, showPageTitle + "_DoChange", (message) =>
            {
                HashSet<Control> tempHashSet = SysCommon.getCurrentControl(showPageTitle);
                if (tempHashSet.Count > 0)
                {
                    DoChanged(tempHashSet);
                }
            });
        }
        /// <summary>
        /// 初始化线程
        /// </summary>
        private void initThread()
        {
            // 标签值变化监听线程
            tagInfoSyncThread = new Thread(syncThreadFunc);
            tagInfoSyncThread.SetApartmentState(ApartmentState.STA);
            tagInfoSyncThread.IsBackground = true;
            tagInfoSyncThread.Start();
        }

        /// <summary>
        /// 标签值变化监听
        /// </summary>
        private void syncThreadFunc()
        {
            // 创建消费者对象
            IConsumer<string, object> KafkaConsumer = KafkaHelper.GetConsumer();
            while (true)
            {
                if (SystemConfig.systemState == "预检测" || SystemConfig.systemState == "可见许可")
                {
                    PreDetectionVisibility = Visibility.Visible;
                }
                else
                {
                    PreDetectionVisibility = Visibility.Hidden;
                }
                // 网络中断不进行消费监听
                if (SystemConfig.SystemStatus == "网络中断")
                {
                    Thread.Sleep(1000);
                    continue;
                }
                if (ThreadController.RoundBarCastWellPublicAuxiliaryThreadState)
                {
                    //开始消费
                    var result = KafkaConsumer.Consume();
                    if (result != null)
                    {
                        //手动提交
                        KafkaConsumer.Commit(result);
                        //获取消息内容
                        string tagId = result.Message.Value.ToString();
                        HashSet<Control> hashSet = KafkaHelper.UpdateCurrentUserTagValue(Int32.Parse(tagId), KafkaHelper.GetTagValueByKey(tagId.ToString()), showPageTitle);
                        if (hashSet != null)
                        {
                            DoChanged(hashSet);
                        }
                    }
                }
                Thread.Sleep(10);
            }
        }

        /// <summary>
        /// 执行动作
        /// </summary>
        /// <param name="hashSet"></param>
        private void DoChanged(HashSet<Control> hashSet)
        {

            //遍历返回的控件信息刷新对应的控件
            foreach (Control item in hashSet)
            {
                switch (item.ControlName)
                {
                    /** 气体润滑按钮 **/
                    case "Button_AutoGasLubrication":
                        Button_AutoGasLubrication_Value = TagTool.GetTagValueByFormNameAndControlName(showPageTitle, item.ControlName) == "false" ? false : true;
                        break;
                    case "Button_ManualGasLubrication":
                        Button_ManualGasLubrication_Value = TagTool.GetTagValueByFormNameAndControlName(showPageTitle, item.ControlName) == "false" ? false : true;
                        break;
                    case "Button_ForwardGasLubrication":
                        Button_ForwardGasLubrication_Value = TagTool.GetTagValueByFormNameAndControlName(showPageTitle, item.ControlName) == "false" ? false : true;
                        break;
                    case "Button_ReversalGasLubrication":
                        Button_ReversalGasLubrication_Value = TagTool.GetTagValueByFormNameAndControlName(showPageTitle, item.ControlName) == "false" ? false : true;
                        break;
                    /** 送丝机按钮 **/
                    case "Button_AutoFeederLubrication":
                        Button_AutoFeederLubrication_Value = TagTool.GetTagValueByFormNameAndControlName(showPageTitle, item.ControlName) == "false" ? false : true;
                        break;
                    case "Button_ManualFeederLubrication":
                        Button_ManualFeederLubrication_Value = TagTool.GetTagValueByFormNameAndControlName(showPageTitle, item.ControlName) == "false" ? false : true;
                        break;
                    case "Button_ForwardFeeder":
                        Button_ForwardFeeder_Value = TagTool.GetTagValueByFormNameAndControlName(showPageTitle, item.ControlName) == "false" ? false : true;
                        break;
                    case "Button_ReversalFeeder":
                        Button_ReversalFeeder_Value = TagTool.GetTagValueByFormNameAndControlName(showPageTitle, item.ControlName) == "false" ? false : true;
                        break;
                    default:
                        /** 刷新页面值变化信息 **/
                        RaisePropertyChanged(item.ControlName);
                        break;
                }
            }
        }

        /// <summary>
        /// 初始化命令
        /// </summary>
        private void initCommand()
        {
            // 气体润滑按钮点击触发
            GusButtonCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(gusButtonHandler)
            };
            // 送丝机按钮点击触发
            FeederButtonCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(feederButtonHandler)
            };
            /**
             * 按钮命令
             * 气体润滑设置：SP、CV
             * 送丝机设置：SP、CV
             * **/
            ShowModalPanelCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(showModalPanelHandler)
            };
        }

        /// <summary>
        /// 按钮弹框
        /// </summary>
        /// <param name="obj"></param>
        private void showModalPanelHandler(object obj)
        {
            string param = obj.ToString();
            switch (param)
            {
                // 气体润滑SP设置
                case "Button_SP_Gas":
                    WindowManager.ShowModalDigitalInputPanel("SetCVPanel", showPageTitle + "Button_SP_Gas", Button_SP_Gas);
                    break;
                // 气体润滑CV设置
                case "Button_CV_Gas":
                    WindowManager.ShowModalDigitalInputPanel("SetCVPanel", showPageTitle + "Button_CV_Gas", Button_CV_Gas);
                    break;
                // 气送丝机SP设置
                case "Button_SP_Feeder":
                    WindowManager.ShowModalDigitalInputPanel("SetCVPanel", showPageTitle + "Button_SP_Feeder", Button_SP_Feeder);
                    break;
                // 气送丝机CV设置
                case "Button_CV_Feeder":
                    WindowManager.ShowModalDigitalInputPanel("SetCVPanel", showPageTitle + "Button_CV_Feeder", Button_CV_Feeder);
                    break;
                default:
                    break;
            }
        }

        /// <summary>
        /// 气体润滑按钮点击触发
        /// </summary>
        /// <param name="obj"></param>
        private void gusButtonHandler(object obj)
        {
            BusinessCmd setTagValueMsg = new BusinessCmd
            {
                Guid = Guid.NewGuid().ToString(),
                BusinessCmdCode = 3,
                TagId = TagTool.GetTagIdByValueByFormNameAndControlName(showPageTitle, obj.ToString()),
                TagValue = "true"
            };
            // 发送消息
            KafkaHelper.SendGatewayBusinessCmd(setTagValueMsg);
        }

        /// <summary>
        /// 送丝机按钮点击触发
        /// </summary>
        /// <param name="obj"></param>
        private void feederButtonHandler(object obj)
        {
            BusinessCmd setTagValueMsg = new BusinessCmd
            {
                Guid = Guid.NewGuid().ToString(),
                BusinessCmdCode = 3,
                TagId = TagTool.GetTagIdByValueByFormNameAndControlName(showPageTitle, obj.ToString()),
                TagValue = "true"
            };
            // 发送消息
            KafkaHelper.SendGatewayBusinessCmd(setTagValueMsg);
        }
        #endregion 方法


    }
}
